from django       import forms
from bb.models    import Topic, Talk, Board
import pdb

class TopicForm(forms.ModelForm):
    body = forms.CharField(widget=forms.Textarea)

    def __init__(self, *args, **kwargs):
        self.user  = kwargs.pop('user',  None)
        self.board = kwargs.pop('board', None)
        self.ip    = kwargs.pop('ip',    None)
        super(TopicForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        t = Topic.objects.create(\
                title            = self.cleaned_data['title'],
                board            = self.board,
                author           = self.user,
                last_talk_author = self.user,
        )
        t.save()
        talk = Talk.objects.create(\
                board  = self.board,
                title  = self.cleaned_data['title'],
                topic  = t,
                body   = self.cleaned_data['body'],
                author = self.user,
                ip     = self.ip,
        )
    
        board = Board.objects.get(pk=t.board.id)
        board.last_topic = t.id
        board.topics += 1
        board.save()
    
    class Meta:
        model = Topic
        exclude = ['hits', 'replies', 'board', 'author', 'ip', 'last_talk_author']
        #fields ['title']
        
class TalkForm(forms.ModelForm):
    body = forms.CharField(widget=forms.Textarea)
    
    def __init__(self, *args, **kwargs):
        self.user  = kwargs.pop('user',  None)
        self.topic = kwargs.pop('topic', None)
        self.board = kwargs.pop('board', None)
        self.ip    = kwargs.pop('ip',    None)
        
        super(TalkForm, self).__init__(*args, **kwargs)
        
    def save(self, commit=True):        
        t = Talk.objects.create(\
            title  = "RE:%s"%self.topic.title,
            body   = self.cleaned_data['body'],
            ip     = self.ip,
            author = self.user,
            board  = self.board,
            topic  = self.topic,
        )
        t.save()
        
        self.topic.replies += 1
        self.topic.last_talk_datetime = t.created
        self.topic.last_talk_author   = t.author
        self.topic.save()
        
        self.board.replies += 1
        self.board.save()
        
        
    
    class Meta:
        model = Talk
        exclude = ['board', 'author', 'ip', 'topic', 'title']
    